package com.easy.work.function.me;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.andview.refreshview.utils.Utils;
import com.base.syslib.Logs;
import com.base.syslib.impl.OneChoiceImpl;
import com.base.syslib.util.DensityUtil;
import com.base.syslib.util.MessageTools;
import com.base.syslib.util.SequenceUtil;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.app.CommonValue;
import com.easy.work.bean.WithdrawBean;
import com.easy.work.function.mall.bean.DeleteEvent;
import com.easy.work.function.mall.bean.JobCommonBean;
import com.easy.work.function.me.adapter.PictureAdapter;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CashDrawRequest;
import com.easy.work.http.request.EducationRequest;
import com.easy.work.oss.UICallback;
import com.easy.work.utils.UserOssUtils;
import com.easy.work.view.NoScrollGridView;
import com.squareup.picasso.Picasso;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPicker;

/**
 * @author zhangfeng
 * @date 2017/12/28
 * @desc 现金提现
 */

public class CashDrawActivity extends BaseActivity {

    private static final String TAG = CashDrawActivity.class.getSimpleName();
    /**
     * 显示图片
     */
    @BindView(R.id.gv)
    NoScrollGridView gridView;
    @BindView(R.id.tv_employ_company)
    TextView tvEmployCompany;
    @BindView(R.id.tv_employ_time)
    TextView tvEmployTime;
    @BindView(R.id.tv_draw_money)
    TextView tvDrawMoney;
    @BindView(R.id.iv_company)
    ImageView ivCompanyPicture;
    @BindView(R.id.tv_photo_desc)
    TextView tvPhotoDesc;
    @BindView(R.id.et_card_number)
    EditText etCardNumber;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_bank_name)
    TextView tvBankName;
    @BindView(R.id.et_bank_dot)
    EditText etBankDot;
    @BindView(R.id.btn_submit)
    Button btnSubmit;
    List<JobCommonBean.ItemsEntity> bankList;
    private WithdrawBean withdrawBean;

    private PictureAdapter mAdapter;
    private List<String> mList = new ArrayList<>();
    private UserOssUtils ossUtils;

    /**
     * 提现请求
     */
    private CashDrawRequest request = new CashDrawRequest();

    public static void start(Context ctx, WithdrawBean withdrawBean) {
        Intent intent = new Intent(ctx, CashDrawActivity.class);
        intent.putExtra("withdrawBean", withdrawBean);
        ctx.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cash_draw);
        ButterKnife.bind(this);
        initTitle("现金提现");

        if (getIntent() != null && getIntent().hasExtra("withdrawBean")) {
            withdrawBean = (WithdrawBean) getIntent().getSerializableExtra("withdrawBean");
            tvEmployCompany.setText("录用公司：" + withdrawBean.companyName);
            tvEmployTime.setText("录用时间：" + withdrawBean.employedDate);
            tvDrawMoney.setText("提现金额：" + withdrawBean.cashBackNum + "元");
            Picasso.with(oThis).load(withdrawBean.companyImage).error(R.mipmap.icon_zhaopintiaojian).into(ivCompanyPicture);

        }

        int margin = (Utils.getScreenWidth(this) - DensityUtil.dip2px(this, 50)) / 4;
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) tvPhotoDesc.getLayoutParams();
        lp.leftMargin = margin;
        tvPhotoDesc.setLayoutParams(lp);
        ossUtils = new UserOssUtils(this, null);
        ossUtils.initOssData();
        initGridView();
        getDictionaryList("es.base.dictionary.Bank", "Bank");
    }

    private void initGridView() {
        mList.add("");
        mAdapter = new PictureAdapter(this, 1, mList);
        gridView.setAdapter(mAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Logs.e(TAG, "position:" + position);
                // 最多只能添加7张图片
                if (mAdapter.getCount() - 1 == position) {
                    if (mAdapter.getCount() - 1 < 7) {
                        PhotoPicker.builder()
                                .setPhotoCount(7 - mAdapter.getCount() + 1)
                                .setShowCamera(true)
                                .setShowGif(false)
                                .setPreviewEnabled(false)
                                .start(CashDrawActivity.this, PhotoPicker.REQUEST_CODE);
                    } else {
                        MessageTools.showToast(getApplicationContext(), "无法再添加更多图片了");
                    }
                }
            }
        });

        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.getCount() - 1 != position) {
                    showNoticeDialog(mList.get(position), position);
                    return false;
                }
                return true;
            }
        });
    }

    /**
     * 提示用户是否确定删除
     *
     * @param path 文件路径
     */
    private void showNoticeDialog(final String path, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(CashDrawActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("确定要删除该张图片吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                objectImgNames.remove(position);
                mList.remove(path);
                mAdapter.notifyDataSetChanged();
                if (mAdapter.getCount() == 1) {
                    tvPhotoDesc.setVisibility(View.VISIBLE);
                }
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == PhotoPicker.REQUEST_CODE) {
            if (data != null) {
                photos.clear();
                photos = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                if (photos.size() > 0) {
                    Logs.e(TAG, "filePath:" + photos.toString());
                    showMyDialog("正在上传图片");
                    upLoadHandler.sendEmptyMessage(posUpload);
//                    mList.addAll(mList.size() - 1, photos);
//                    mAdapter.notifyDataSetChanged();
//
                }
            }
        }
    }

    /**
     * 每次选择的图片列表
     * 中间变量，使用完清空
     */
    private ArrayList<String> photos = new ArrayList<>();
    /**
     * 每张图对应的oss服务器地址，
     */
    private ArrayList<String> objectImgNames = new ArrayList<>();
    private int posUpload = 0;

    /**
     * 上传图片
     */
    private Handler upLoadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int what = msg.what;
            if (what < photos.size()) {
                String filePath = photos.get(msg.what);
                upLoadImg(filePath);
                tvPhotoDesc.setVisibility(View.GONE);
            } else if (what == photos.size()) {
                posUpload = 0;
                MessageTools.showToast(oThis, "图片上传结束");
                closeDialog();
            }
        }
    };

    /**
     * 上传图片
     * 命名
     */
    private void upLoadImg(final String filePath) {

        SequenceUtil sequenceUtil = SequenceUtil.getInstance();
//        String url = UserOssUtils.uploadUrl + CommonValue.contractImage + AppSession.getInstance().getUserId() + "/" + sequenceUtil.getRandomID() + ".png";
        String url = CommonValue.contractImage + AppSession.getInstance().getUserId() + "/" + sequenceUtil.getRandomID() + ".png";
        ossUtils.asyncTaskUpload(url, filePath, getPutCallback(null, filePath, UserOssUtils.uploadUrl + url));
    }

    // 普通上传回调
    public UICallback<PutObjectRequest, PutObjectResult> getPutCallback(final ImageView view, final String imageName, final String url) {

        return new UICallback<PutObjectRequest, PutObjectResult>(ossUtils.UIDispatcher) {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                posUpload++;
                Logs.d(tag, "UploadSuccess");

                addCallback(new Runnable() {
                    @Override
                    public void run() {

                        upLoadHandler.sendEmptyMessage(posUpload);
                        objectImgNames.add(url);
                        mList.add(mList.size() - 1, imageName);
//                        mList.add(imageName);
                        mAdapter.notifyDataSetChanged();

                    }
                }, null);

                super.onSuccess(request, result);
            }


            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {
                posUpload++;
                upLoadHandler.sendEmptyMessage(posUpload);
                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Logs.e("ErrorCode", serviceException.getErrorCode());
                    Logs.e("RequestId", serviceException.getRequestId());
                    Logs.e("HostId", serviceException.getHostId());
                    Logs.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);

                mHandler.sendEmptyMessage(CommonValue.MSG_LOAD_ERROR);
                ossUtils.ossService.stopPutLoad();
            }
        };
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CommonValue.MSG_LOAD_SUCCES:
                    //图片上传成功
                    closeDialog();
                    break;
                case CommonValue.MSG_LOAD_ERROR:
                    MessageTools.showToast(oThis, "第" + posUpload + "二张图片上传失败！");
                    break;

            }
        }
    };

    private void cashDraw() {
        if (objectImgNames.size() < 1) {
            MessageTools.showToast(getApplicationContext(), "请先添加合同图片");
            return;
        }
//        List<String> pictureList = new ArrayList<>();
//        pictureList.addAll(mAdapter.getList());
//        pictureList.remove(pictureList.size() - 1);

        String cardNumber = etCardNumber.getText().toString();
        if (TextUtils.isEmpty(cardNumber)) {
            MessageTools.showToast(getApplicationContext(), "请输入银行卡号");
            return;
        }

        String name = etName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            MessageTools.showToast(getApplicationContext(), "请输入您的姓名");
            return;
        }

        String bankName = tvBankName.getText().toString();
        if (TextUtils.isEmpty(bankName)) {
            MessageTools.showToast(getApplicationContext(), "请输入银行名称");
            return;
        }

        String bankDot = etBankDot.getText().toString();
        if (TextUtils.isEmpty(bankDot)) {
            MessageTools.showToast(getApplicationContext(), "请输入银行网点");
            return;
        }

        showDialog();

        request.cashApplyId = withdrawBean.cashApplyId;
        request.cardNum = cardNumber;
        request.name = name;
        request.bankBranch = bankDot;
        request.pictureList = objectImgNames;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                closeDialog();
                MessageTools.showToast(getApplicationContext(), "提现成功");
                EventBus.getDefault().post(withdrawBean);
                finish();
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                closeDialog();
                MessageTools.showToast(getApplicationContext(), msg);
            }
        });
    }

    @OnClick(R.id.btn_submit)
    void cashWithDraw() {
        cashDraw();
    }


    /**
     * 获取字典数据
     *
     * @param dicId 字典
     * @param key   判断学历还是薪资
     */
    private void getDictionaryList(String dicId, final String key) {
        final EducationRequest request = new EducationRequest();
        request.dicId = dicId;
        request.parentKey = "";
        request.sliceType = "3";
        request.query = "";
        request.start = 0;
        request.limit = 0;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                handleData(response, key);
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
            }
        });
    }

    /**
     * 学历或薪资数据处理
     */
    private void handleData(BaseResponse response, String key) {
        JobCommonBean bean = (JobCommonBean) response;
        if (bean != null && bean.items != null && !bean.items.isEmpty()) {
            List<JobCommonBean.ItemsEntity> list = bean.items;
            if (key.equals("Bank")) {
                bankList = list;
            }
        }
    }

    /**
     * 选择学历
     * JobCommonList
     */
    private void selectBank() {
        String[] types;
        if (bankList == null || bankList.size() < 1) {
            getDictionaryList("es.base.dictionary.Bank", "Bank");
            MessageTools.showToast(this, "正在获取银行列表");
            return;
        }
        int size = bankList.size();
        types = new String[size];
        for (int i = 0; i < size; i++) {
            types[i] = bankList.get(i).text;
        }
        MessageTools.showOneChoiceDialog(this, "请选择银行", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvBankName.setText(text);
                if (bankList == null || bankList.size() < 1) {
                    int bankID = Integer.parseInt(bankList.get(position).key);
                    request.bank = bankID;
                }
            }
        });
    }

    @OnClick(R.id.tv_bank_name)
    public void onViewClicked() {
        selectBank();
    }
}
